<?php

namespace app\m\controller;

use think\Db;

/**
 * 小程序功能基类
 * Class Base
 * @package app\m\controller
 */
class Base
{
    private $app_id = 'wx62408395b73989a9';

    private $secret_key = 'efe90119b8981104e55453bbb047ec1c';


    /**
     * 设置session信息，如果设置成功返回true
     */
    protected function ses(&$rev, &$ses)
    {
        if (isset($_GET['_c'])) {
            $str = file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->app_id . '&secret=' . $this->secret_key . '&js_code=' . $_GET['_c'] . '&grant_type=authorization_code');
            //loger($str,'wx_auth');
            $res = json_decode($str, true);
            if (isset($res['openid'])) {
                $openid = $res['openid'];
                $now = $_SERVER['REQUEST_TIME'];
                // 查询记录
                $qs = Db::query('select id,uid,nickname,avatar,update_time from wx_ac where openid=?', [$openid]);
                if ($qs) {
                    $ac = $qs[0];
                    $oid = $ac['id'];
                    $uid = $ac['uid'];
                    $rev['uAuth'] = ($now - $ac['update_time']) > 86400 ? 1 : 0; // 一天更新一次
                    unset($ac['update_time'], $ac['id']);

                    $avatar = empty($ac['avatar']) ? 'https://c.g56.cn/x9/user_im.png' : $ac['avatar'];

                    $ac['avatar'] = $avatar;

                } else {
                    // 不自动注册一个新用户
                    $uid = 0; //  Db::table('user')->insertGetId(['time' => $now, 'sce' => '1']); // sce=>1:小程序自动创建

                    $oid = Db::table('wx_ac')->insertGetId(['openid' => $openid, 'uid' => $uid, 'create_time' => $now]);

                    $ac = ['nickname' => '', 'avatar' => 'https://c.g56.cn/x9/user_im.png', 'uAuth' => 1]; // 'id' => $oid,
                }

                $ses = ['oid' => $oid, 'uid' => $uid, 'key' => $res['session_key']];
                session('ses', $ses);
                $rev['user'] = $ac;
                $rev['ssc'] = 'PHPSESSID=' . session_id();  // 'PHPSESSID=' + ret.data.sid
                return true;
            } else
                loger($str, 'wx_auth_err');
        }
        return false;
    }

}